package com.oscar.ehome.view.pageview;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.MingpianBean;
import com.oscar.ehome.bean.pagebean.mingpianjson;
import com.oscar.ehome.bean.setbean.FeedBackBean;
import com.oscar.ehome.bean.setbean.TokenBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.upload.OnUploadListener;
import com.oscar.ehome.utils.upload.UploadUtil;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.MyEditText;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.MingpianView;
import com.yanzhenjie.album.Album;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by juxing
 * author: SunHaoZhao
 * date: On 2018/2/1
 */

public class MingPianActivity extends BasesActivity<MingpianView, PagePresenter> implements MingpianView, OnUploadListener, View.OnClickListener {

    PagePresenter pagePresenter;
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    @BindView(R.id.title_tv_menu)
    TextView titleTvMenu;
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    @BindView(R.id.titlebar_img_right)
    ImageView titlebarImgRight;
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;
    @BindView(R.id.right_layout)
    RelativeLayout rightLayout;
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.nameidit)
    EditText nameidit;
    @BindView(R.id.xingxiangimg)
    ImageView xingxiangimg;
    @BindView(R.id.ll_addView)
    LinearLayout addHotelNameView;

    @BindView(R.id.weixinpicture)
    ImageView weixinpicture;
    @BindView(R.id.quesiton_tj)
    Button quesiton_tj;
    String token = "";
    String gerenzhao, weixinma;
    //装在所有动态添加的Item的LinearLayout容器
    private UploadUtil mUploadUtil;
    private String type;
    private String uptoken = "";
    int index;
    public List<String> ImageList = new ArrayList<>();//上传图片
    public List<String> jingliimglist = new ArrayList<>();//上传图片
    Gson gson = new Gson();
    List<mingpianjson> persons = new ArrayList<>();
    String name;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mingpiantianjia);
        ButterKnife.bind(this);
        initView();
        //默认添加一个Item
        addViewItem();
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

    public void initView() {
        CommonUtils.url_code = 1;

        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleTopbar.setText("名片");
        titleImgBack.setOnClickListener(this);
        token = SystemConfigFactory.getInstance(MingPianActivity.this).getSystemConfig().getToken();
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(MingPianActivity.this).getSystemConfig().getColor()));
        xingxiangimg.setOnClickListener(this);
        TintManager.setTint(quesiton_tj, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        quesiton_tj.setOnClickListener(this);
        weixinpicture.setOnClickListener(this);
        pagePresenter.getmingpiantoken();
        mUploadUtil = new UploadUtil();
        mUploadUtil.setOnUploadListener(this);
        pagePresenter.getmingpianinfo(token);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.weixinpicture:
                type = "2";
                Album.startAlbum(MingPianActivity.this, 400, 1);
                break;
            case R.id.xingxiangimg:
                type = "1";
                Album.startAlbum(MingPianActivity.this, 400, 1);

                break;
            case R.id.title_img_back:
                finish();
                break;
            case R.id.tianjiaimg://点击添加按钮就动态添加Item
                if (!nameidit.getText().toString().equals("")) {
                    if (gerenzhao != null && !gerenzhao.equals("")) {

                        if (weixinma != null && !weixinma.equals("")) {
                            Log.e("mingpianwenti", "onClick: " + addHotelNameView.getChildCount());
                            for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
                                View childAt = addHotelNameView.getChildAt(i);
                                EditText hotelName = childAt.findViewById(R.id.biaotiedit);
                                MyEditText neirong = childAt.findViewById(R.id.jianjieedit);
                                if (!hotelName.getText().toString().equals("") && !neirong.getText().toString().equals("") && jingliimglist.size() > i) {
                                    if (i == addHotelNameView.getChildCount() - 1) {
                                        addViewItem();
                                        return;
                                    }
                                } else {
                                    ToastUtil.show(MingPianActivity.this, "您第" + (i + 1) + "组没有填写完整，请完善");
                                }

                            }
                        } else {
                            ToastUtil.show(MingPianActivity.this, "请上传微信二维码");
                        }
                    } else {
                        ToastUtil.show(MingPianActivity.this, "请上传个人形象照");
                    }
                } else {
                    ToastUtil.show(MingPianActivity.this, "请填写姓名");
                }


                break;
            case R.id.quesiton_tj://打印数据
                SubmitFeedBack();

                break;
        }
    }

    private void SubmitFeedBack() {
        CommonUtils.url_code = 0;
        //判断为空
        if (!nameidit.getText().toString().equals("")) {
            if (gerenzhao != null && !gerenzhao.equals("")) {

                if (weixinma != null && !weixinma.equals("")) {
                    for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
                        View childAt = addHotelNameView.getChildAt(i);
                        EditText hotelName = childAt.findViewById(R.id.biaotiedit);
                        MyEditText neirong = childAt.findViewById(R.id.jianjieedit);
                        if (!hotelName.getText().toString().equals("") && !neirong.getText().toString().equals("") && jingliimglist.size() > i) {


                            mingpianjson p = new mingpianjson();
                            p.setTitle(hotelName.getText().toString());
                            p.setExperience(jingliimglist.get(i));
                            p.setIntroduction(neirong.getText().toString());
                            persons.add(p);


                            if (i == addHotelNameView.getChildCount() - 1) {
                                name = nameidit.getText().toString();

                                showLoading();
                                String str = gson.toJson(persons);
                                pagePresenter.mingpianfankui(token, name, str, gerenzhao, weixinma);
                            }
                        } else {
                            persons.clear();
                            ToastUtil.show(MingPianActivity.this, "您第" + (i + 1) + "组没有填写完整，请完善");
                        }
                    }
                } else {
                    persons.clear();
                    ToastUtil.show(MingPianActivity.this, "请上传微信二维码");
                }
            } else {
                persons.clear();
                ToastUtil.show(MingPianActivity.this, "请上传个人形象照");
            }
        } else {
            persons.clear();
            ToastUtil.show(MingPianActivity.this, "请填写姓名");
        }
        //获取手机品牌
    }

    /**
     * Item排序
     */
    private void sortHotelViewItem() {
        //获取LinearLayout里面所有的view
        for (int i = 0; i < addHotelNameView.getChildCount(); i++) {
            final View childAt = addHotelNameView.getChildAt(i);
            final ImageView btn_remove = childAt.findViewById(R.id.shanchuimg);
            ImageView jingliimg = childAt.findViewById(R.id.jinglipicture);
            btn_remove.setTag("remove");//设置删除标记

            btn_remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //从LinearLayout容器中删除当前点击到的ViewItem
                    if (addHotelNameView.getChildCount() > 1) {
                        addHotelNameView.removeView(childAt);
                        sortHotelViewItem();
                    } else {
                        ToastUtil.show(MingPianActivity.this, "仅剩一组，无法删除");
                    }

                }
            });
            jingliimg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    index = ((ViewGroup) childAt.getParent()).indexOfChild(childAt);
                    type = "3";
                    Album.startAlbum(MingPianActivity.this, 400, 1);


                }
            });
            //如果是最后一个ViewItem，就设置为添加
            if (i == (addHotelNameView.getChildCount() - 1)) {
                LinearLayout btn_add = childAt.findViewById(R.id.tianjiaimg);
                btn_add.setVisibility(View.VISIBLE);
                btn_add.setTag("add");
                btn_add.setOnClickListener(this);

            } else {
                LinearLayout btn_add = childAt.findViewById(R.id.tianjiaimg);
                btn_add.setVisibility(View.GONE);

            }
        }
    }

    //添加ViewItem
    private void addViewItem() {
        if (addHotelNameView.getChildCount() == 0) {//如果一个都没有，就添加一个
            View hotelEvaluateView = View.inflate(this, R.layout.mingpianitem, null);
            LinearLayout btn_add = hotelEvaluateView.findViewById(R.id.tianjiaimg);
            btn_add.setVisibility(View.VISIBLE);
            btn_add.setTag("add");
            btn_add.setOnClickListener(this);
            addHotelNameView.addView(hotelEvaluateView);
            sortHotelViewItem();
        } else {//如果有一个以上的Item,点击为添加的Item则添加
            View hotelEvaluateView = View.inflate(this, R.layout.mingpianitem, null);
            addHotelNameView.addView(hotelEvaluateView);
            sortHotelViewItem();


        }

    }

    @Override
    public void onAllSuccess() {


        Log.d("mwh", "文件" + "全部上传成功");
    }

    @Override
    public void onAllFailed() {

        Log.d("mwh", "文件" + "全部失败");
    }

    @Override
    public void onThreadProgressChange(int position, int percent) {
        Log.d("mwh", "文件" + position + "上传" + percent + "%");

    }

    @Override
    public void onThreadFinish(int position, String keys) {
        switch (type) {
            case "1":
                gerenzhao = keys;
                break;
            case "2":
                weixinma = keys;
                break;
            default:
                if (jingliimglist.size() < (index + 1) || jingliimglist.get(index) == null) {
                    jingliimglist.add(keys);
                } else {
                    jingliimglist.set(index, keys);
                }
        }

    }

    @Override
    public void onThreadInterrupted(int position) {

    }


    @Override
    public void getmingpiantoken(TokenBean tokenBean) {
        uptoken = tokenBean.getUptoken();
    }

    @Override
    public void getmingpianinfo(MingpianBean result) {
        if (!result.equals("")) {
            Intent in = getIntent();
            if (in.getStringExtra("bianji") != null && in.getStringExtra("bianji").equals("bianji")) {

                nameidit.setText(result.getName());
                gerenzhao = result.getImage();
                weixinma = result.getQrCode();
                GildeUtils.loadUrlImages(C.qiniu + result.getImage(), xingxiangimg, this);
                GildeUtils.loadUrlImages(C.qiniu + result.getQrCode(), weixinpicture, this);

                for (int i = 0; i < result.getList().size(); i++) {
                    if (i > 0) {
                        addViewItem();
                    }
                    View childAt = addHotelNameView.getChildAt(i);
                    EditText hotelName = childAt.findViewById(R.id.biaotiedit);
                    MyEditText neirong = childAt.findViewById(R.id.jianjieedit);
                    ImageView jinglitu = childAt.findViewById(R.id.jinglipicture);
                    hotelName.setText(result.getList().get(i).getTitle());
                    neirong.setText(result.getList().get(i).getIntroduction());
                    GildeUtils.loadUrlImages(C.qiniu + result.getList().get(i).getExperience(), jinglitu, this);
                    jingliimglist.add(result.getList().get(i).getExperience());
                }
//
            }
        }
    }

    @Override
    public void mingpianfankui(FeedBackBean feedBackBean) {
        dismissLoading();
        Intent in = new Intent();
        SystemConfigFactory.getInstance(MingPianActivity.this).getSystemConfig().setyaoqing(feedBackBean.getObject());
        in.putExtra("contentsrc", feedBackBean.getObject());
        in.putExtra("type", "yaoqing");
        in.putExtra("name", "名片");
        in.putExtra("people", name);
        in.putExtra("touxiang", gerenzhao);
        in.setClass(MingPianActivity.this, BannerWebActivity.class);
        startActivity(in);
        finish();
    }

    @Override
    public void erroy() {

    }

    @Override
    public void erry(String result) {
        dismissLoading();
        if (result.equals("tiaoguo")) {
        } else {
            Toast.makeText(MingPianActivity.this, result, Toast.LENGTH_SHORT).show();
        }
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(MingPianActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(MingPianActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 400) {
            if (resultCode == RESULT_OK) { // 判断是否成功。
                // 拿到用户选择的图片路径List：
                ImageList.clear();
                ImageList = Album.parseResult(data);

                if ("".equals(uptoken)) {
                    pagePresenter.getmingpiantoken();
                } else {
                    if (ImageList.size() > 0) {
                        startUpload();
                    }
                }
                if (type.equals("1")) {
                    GildeUtils.loadUrlImages(ImageList.get(0), xingxiangimg, this);
                } else if (type.equals("2")) {
                    GildeUtils.loadUrlImages(ImageList.get(0), weixinpicture, this);
                } else {
                    final View childAt = addHotelNameView.getChildAt(index);
                    ImageView jingliimg = childAt.findViewById(R.id.jinglipicture);
                    GildeUtils.loadUrlImages(ImageList.get(0), jingliimg, this);

                }

            }
        }
    }

    private void startUpload() {//模拟上传文件

        mUploadUtil.submitAll(ImageList, uptoken);
    }

}